package top.chukongxiang.dubboboot.simple.common.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;

public class ByteBufUtils {


    /**
     * 向ByteBuf写入定长字符串
     * <p></p>
     * 若字符串长度大余指定长度，则截取，若小于则补零
     ***/
    public static void writeFixLength(ByteBuf buf, String data, int length) {
        byte[] bytes = data.getBytes(CharsetUtil.UTF_8);
        int blen = bytes.length;

        int wlen = blen > length ? length : blen;
        buf.writeBytes(bytes, 0, wlen);
        if (wlen < length) {
            buf.writeZero(length - wlen);
        }
    }


    /**
     * 创建发送buf,
     * 协议头+请求指令
     */
    public static ByteBuf createMessage(int cmd) {
        ByteBuf msg = Unpooled.buffer();
        msg.writeBytes("HSDFYJ".getBytes());
        msg.writeByte(cmd);
        return msg;
    }
}
